package com.ruoyi.system.task;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.lang.Console;
import cn.hutool.core.util.RandomUtil;
import com.ruoyi.system.domain.TBOrderSpread;
import com.ruoyi.system.service.ITBCustomerService;
import com.ruoyi.system.service.ITBOrderSpreadService;
import com.ruoyi.system.util.MessageUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 *  短信发送任务
 *
 * @author taochunbao
 */
@Component("messageTask")
public class MessageTask {
    @Autowired
    private ITBOrderSpreadService orderSpreadService;
    public void run()
    {
        try {
            //获取要发短信的手机号
            List<Map> maps = orderSpreadService.selectMessageTel();
            List<Map<String,Object>> fileList = new ArrayList<>();
            Map<String,Integer> orderMap = new HashMap<>();
            for (Map map : maps) {
                System.out.println(map);
                String orderNum = map.get("orderNum").toString();//订单号
                if(!orderMap.containsKey(orderNum)){
                    orderMap.put(orderNum,1);
                    fileList.add(map);
                }else{
                    orderMap.put(orderNum, Convert.toInt(orderMap.get(orderNum))+1);
                }
            }
            for (Map map : fileList) {
                Long id = Convert.toLong(map.get("id"));//订单号
                String orderNum = map.get("orderNum").toString();//订单号
                String customerName = map.get("customerName").toString();//客户名称
                String phone = map.get("phone").toString();//手机号
                String orMoney = map.get("orMoney").toString();//订单金额
                String exdays = map.get("exdays").toString();//逾期通知天数
                Long exDaysNum = Convert.toLong(exdays);
                String xh = map.get("xh").toString();//通知时间间隔
                String spNum = map.get("spNum").toString();//分期期数
                String reTime = map.get("reTime").toString();//还款日期
                String reMoney = map.get("reMoney").toString();//还款金额
                String spCount=orderMap.get(orderNum).toString();
                Object lastTimeObj = map.get("lastTime");//上次通知时间
                map.put("spCount",spCount);
                String code = RandomUtil.randomNumbers(4);
                //判断是否满足逾期条件，判断是否需要循环通知
                String rTime = reTime+" 00:00:00";
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                String nowTime = sdf.format(new Date())+" 00:00:00";
                long days = BetweenDays(rTime, nowTime);
                if(days>=exDaysNum){//超过逾期天数
                    String params = "{\"code\":\""+code+"\"}";
                    Long xhTime = Convert.toLong(xh);//通知时间间隔
                    if(xhTime<=0&&lastTimeObj==null){
                        //仅发送一次
                        sendMsg(id,phone,params,orderSpreadService);//发送短信测试...
                    }else{
                        //比较上次通知时间与当前时间差，是否大于 xhTime
                        Long lastTime = Convert.toLong(lastTimeObj);
                        long nTime = new Date().getTime();
                        if(lastTime==null||(nTime-lastTime)>(xhTime*1000*60)){
                            sendMsg(id,phone,params,orderSpreadService);//发送短信测试...
                        }
                    }
                }

            }
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("短信发送失败...");
        }
    }

    public void sendMsg(Long id,String phone,String params,ITBOrderSpreadService orderSpreadService){
        try {
            MessageUtil.sendMsg(phone,params);//发送短信测试...
            //更新上次通知时间
            TBOrderSpread tbOrderSpread = orderSpreadService.selectTBOrderSpreadById(id);
            tbOrderSpread.setLastTime(Convert.toStr(new Date().getTime()));
            orderSpreadService.updateTBOrderSpread(tbOrderSpread);
        } catch (Exception e) {
            e.printStackTrace();
            Console.log("短息发送失败::phone="+phone+"\nparams="+params);
        }
    }

    /**
     * 计算连个日期之间相差的天数
     */
    public long BetweenDays(String dateStr1,String dateStr2) throws ParseException {
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        // 获取日期
        Date date1 = sdf.parse(dateStr1);
        Date date2 = sdf.parse(dateStr2);
        long betweenDays = (date2.getTime() - date1.getTime()) / (1000L*3600L*24L);
        return betweenDays;
    }

}
